//
//  CaogaomanageViewController.m
//  YiqiMobile
//
//  Created by henry on 13-4-28.
//  Copyright (c) 2013年 henry. All rights reserved.
//
#define EDITPOPLISTVIEWTAG 220
#import "CaogaomanageViewController.h"
#import "TogetherViewController.h"
#import "Config.h"
#import "Utility.h"
#import "EditCaogaoViewController.h"
#import "MBProgressHUD.h"
#import "JSON.h"
#import "DefineAction.h"
@interface CaogaomanageViewController ()

@end

@implementation CaogaomanageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
      self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:[Utility customButton:self action:@selector(publishActon:) normalImage:@"caogao_publish_normal.png" lightedImage:@"caogao_publish_hover.png" frame:CGRectMake(0, 0, 59, 31) title:nil tag:20]];
    float height=367;
    if (iPhone5) {
        height+=88;
    }
    
    

	// Do any additional setup after loading the view.
}



-(void) initData:(NSDictionary*) param{
    self.param=param;
     self.navigationItem.titleView=[Utility getTitleView:@"编辑"];
    float height=367;
    if (iPhone5) {
        height+=88;
    }
    self.contentView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, height)];
    self.contentView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:self.contentView];
    EditCaogaoViewController *caogaoViewController=[[EditCaogaoViewController alloc] initWithNibName:@"EditCaogaoViewController" bundle:nil];
    [self addChildViewController:caogaoViewController];
  
    UIViewController *thirdController=[[UIViewController alloc] initWithNibName:nil bundle:nil];
    [self addChildViewController:thirdController];
    
    [self.contentView addSubview:caogaoViewController.view];
    self.currentViewController=caogaoViewController;
    [caogaoViewController loadGonggaoDataFromServer:param];
    [self showSubMenu];
}

-(void) showSubMenu{
    UIView *menuView=[[UIView alloc] initWithFrame:CGRectMake(0,  self.contentView.frame.size.height, 320, 49)];
    menuView.backgroundColor=[UIColor colorWithPatternImage:[Utility imageNamed:@"qzbar_bg.png"]];
    [self.view addSubview:menuView];
    UIButton *button1=[Utility customButton:self action:@selector(onClickbutton:) normalImage:@"eidt_select_normal.png" lightedImage:@"eidt_select_hover.png" frame:CGRectMake(8, 10,  69, 30) title:nil tag:CAOGAOMAINBUTTONTAG+1];
    [menuView addSubview:button1];
    [menuView  addSubview:[Utility customButton:self action:@selector(onClickbutton:) normalImage:@"eidt_order_normal.png" lightedImage:@"eidt_order_hover.png" frame:CGRectMake(87, 10, 69, 30) title:nil tag:CAOGAOMAINBUTTONTAG+2]];
     [menuView  addSubview:[Utility customButton:self action:@selector(onClickbutton:) normalImage:@"eidt_preview_normal.png" lightedImage:@"eidt_preview_hover.png" frame:CGRectMake(166, 10,  69, 30) title:nil tag:CAOGAOMAINBUTTONTAG+3]];
     [menuView  addSubview:[Utility customButton:self action:@selector(onClickbutton:) normalImage:@"eidt_caogao_normal.png" lightedImage:@"eidt_caogao_hover.png" frame:CGRectMake(245, 10,  69, 30) title:nil tag:CAOGAOMAINBUTTONTAG+4]];
    [self onClickbutton:button1];
}


-(IBAction)onClickbutton:(id)sender{
    UIButton *selectButton=(UIButton*)sender;
    int tag=[sender tag]-CAOGAOMAINBUTTONTAG;
    for (int i=1; i<5; i++) {
        UIButton *button=(UIButton*)[self.view viewWithTag:CAOGAOMAINBUTTONTAG+i];
        if (i==tag) {
             selectButton.selected=YES;
        }else{
             button.selected=NO;
        }
        
    }
   
  
    EditCaogaoViewController *firstViewController=[self.childViewControllers objectAtIndex:0];
    UIViewController *thirdController=[self.childViewControllers objectAtIndex:1];
    
    if ((self.currentViewController==thirdController&&tag==3)) {
        return;
    }
    UIViewController *oldViewController=self.currentViewController;
  
    if (tag==3) {
        [self transitionFromViewController:self.currentViewController toViewController:thirdController duration:0.5 options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
            
        }  completion:^(BOOL finished) {
            if (finished) {
                self.currentViewController=thirdController;
            }else{
                self.currentViewController=oldViewController;
            }
        }];
    }else{
        if (tag==1) {
            firstViewController.selectStatus=YES;
             [firstViewController.mytableView setEditing:NO animated:YES];
        }else if(tag==2){
            firstViewController.selectStatus=NO;
            [firstViewController.mytableView setEditing:YES animated:YES];
        }else if(tag==4){
            firstViewController.selectStatus=NO;
             [firstViewController.mytableView setEditing:NO animated:YES];
            [self saveDataToserver:0];
            self.operaflag=0;
        }
         [firstViewController.mytableView reloadData];
        
        if ((self.currentViewController==firstViewController&&(tag==1||tag==2||tag==4))) {
            return;
        }
            [self transitionFromViewController:self.currentViewController toViewController:firstViewController duration:0.5 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
            }  completion:^(BOOL finished) {
                if (finished) {
                    self.currentViewController=firstViewController;
                }else{
                    self.currentViewController=oldViewController;
                }
               
            }];
      
    }
}
-(IBAction)publishActon:(UIButton*)sender{
    [self saveDataToserver:1];
     self.operaflag=1;
    /*NSMutableArray *param=[NSMutableArray array];
    param[0]=@{@"title":@"投稿模块(3选1)",@"list":@[
                       @{@"content":@"社会创新",@"id":@"1"},
                       @{@"content":@"思想文化",@"id":@"2"},
                       @{@"content":@"健康生活",@"id":@"4"}
                       ]};
    param[1]=@{@"title":@"国内标签(多选)",@"list":@[
                       @{@"content":@"技术",@"id":@"4"},
                       @{@"content":@"小资",@"id":@"5"},
                       @{@"content":@"咖啡",@"id":@"6"}
                       ]};
    EditPopListView *editPopListView=(EditPopListView*)[self.view viewWithTag:EDITPOPLISTVIEWTAG];
    if (editPopListView) {
        [editPopListView fadeOut];
        editPopListView=nil;
    }else{
         editPopListView=[[EditPopListView alloc] initWithOptions:param];
        editPopListView.delegate=self;
        editPopListView.tag=EDITPOPLISTVIEWTAG;
        [editPopListView showInView:self.view animated:YES];
    }*/
    
}
/*
- (void)editPopListViewDidSelected:(NSUInteger) category andTags:(NSString*)tags{
    self.categoryId=category;
    self.tags=tags;
    [self publishActon:nil];
    [self saveDataToserver];
      
}

- (void)editPopListViewDidCancel{
    self.categoryId=0;
    self.tags=@"";
     [self publishActon:nil];
}
*/
/*
 ids	N	选用的供稿的ID数组
 type	N	发布方式  0 只保存排序  1 发布  2 投稿
 id	N	投稿的专题ID数组
 b.b0	N	博文ID
 */
-(void) saveDataToserver:(int)type{
    EditCaogaoViewController *editCaogaoViewController=[self.childViewControllers objectAtIndex:0];
    NSArray *ggarray=editCaogaoViewController.ggList;
    NSString *ids=@"";
    for (int i=0; i<[ggarray count]; i++) {
        NSDictionary *dict=[ggarray objectAtIndex:i];
        if ([[dict objectForKey:@"selected"] integerValue]==1) {
          ids=([ids isEqualToString:@""]?[dict objectForKey:@"str1"]:[NSString stringWithFormat:@"%@,%@",ids,[dict objectForKey:@"str1"]]);  
        }
    }
    if (ids.length<2) {
        [Utility customAlertWithMsg:@"请选择草稿" andTitle:ALRRTTITLE andDelagate:nil];
        return;
    }
    [[MBProgressHUD showHUDAddedTo:self.view  animated:NO] setDetailsLabelText:LOADING_TITLE_DEFAULT];
    NSString *url=[NSString stringWithFormat:@"%@/%@",[Utility getServerUrl],UPDATEBFORU];
    NSMutableDictionary *param=[NSMutableDictionary dictionary];
    [param setObject:ids forKey:@"ids"];
    [param setObject:[NSString stringWithFormat:@"%d",type] forKey:@"type"];
    //要注释掉
    [param setObject:[NSString stringWithFormat:@"%d",1] forKey:@"id"];
    [param setObject:[self.param objectForKey:@"str1"] forKey:@"b.b0"];
    self.request=[[URLRequest alloc] initWithPostURL:url andDelegate:self andPostData:param andFile:nil];
    [self.request startLoadData];
}

- (void)requestFinished:(id)context{
    [MBProgressHUD hideAllHUDsForView:self.view  animated:NO];
    @try{
        NSDictionary *result=[context JSONValue];
        if (result!=nil&&[[result objectForKey:@"code"] integerValue]==0) {
            if ([[result  objectForKey:@"method"] isEqual:UPDATEBFORU]) {
                if ( self.operaflag==1) {//发布
                     [Utility customAlertWithMsg:@"发布成功" andTitle:ALRRTTITLE andDelagate:nil];
                    UIViewController *viewController=[[self.navigationController viewControllers] objectAtIndex:0];
                    if ([viewController respondsToSelector:@selector(loadDataFromServer)]) {
                        [viewController performSelector:@selector(loadDataFromServer) withObject:nil];
                        [self.navigationController  popToViewController:viewController animated:YES];
                    }

                }else if(self.operaflag==0){//保存
                    [Utility customAlertWithMsg:@"保存成功" andTitle:ALRRTTITLE andDelagate:nil];
                }
            }
        }else{
            [Utility customAlertWithMsg:PROCESSERROE andTitle:ALRRTTITLE andDelagate:nil];
        }
    }@catch (NSException *e) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
    }
}

- (void)requestFailed:(id)context error:(NSString *)error{
    [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
